package com.shijie.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;

import com.shijie.core.AbstractService;
import com.shijie.domain.entity.UserAddress;
import com.shijie.domain.enums.EnumInterface;
import com.shijie.mapper.UserAddressMapper;

/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@Service
public class UserAddressService extends AbstractService<UserAddress> {

	@Resource
	private UserAddressMapper userAddressMapper;


	public List<UserAddress> selectAddressByUserId(Integer userId) {
		Example condition = new Example(UserAddress.class);
		condition.createCriteria().andEqualTo("userId", userId).andEqualTo("status", EnumInterface.Status.VALID.ordinal());
        condition.orderBy("isDefault").asc();
		return userAddressMapper.selectByCondition(condition);
	}


	public void save(UserAddress userAddress) {

		userAddress.setCreateBy(userAddress.getUserName());
		userAddress.setCreateTime(new Date());
		// 插入的地址 为默认地址
        if (userAddress.getIsDefault() != null && userAddress.getIsDefault().compareTo(EnumInterface.Status.VALID.ordinal()) == 0) {
            // 更新别的地址为非默认地址
            updateOtherUnDefault(userAddress.getUserId(),EnumInterface.Status.INVALID.ordinal());
        }

		userAddressMapper.insertSelective(userAddress);

	}


	public void updateById(UserAddress userAddress) {

        userAddress.setUpdateBy(userAddress.getUserName());
        userAddress.setUpdateTime(new Date());
        // 插入的地址 为默认地址
        if (userAddress.getIsDefault() != null && userAddress.getIsDefault().compareTo(EnumInterface.Status.VALID.ordinal()) == 0) {
            // 更新别的地址为非默认地址
            updateOtherUnDefault(userAddress.getUserId(),EnumInterface.Status.INVALID.ordinal());
        }

        userAddressMapper.updateByPrimaryKeySelective(userAddress);

    }

	private void updateOtherUnDefault(Integer userId,final Integer isDefault) {
        Example con = new Example(UserAddress.class);
        con.createCriteria().andEqualTo("userId", userId);

        List<UserAddress> list = userAddressMapper.selectByCondition(con);
        list.forEach(c -> {
            c.setIsDefault(isDefault);
            userAddressMapper.updateByPrimaryKey(c);
        });


    }

    public void defalutUserAddress(Integer addressId){
		UserAddress userAddress = new UserAddress();
		userAddress.setUpdateBy(userAddress.getUserName());
        userAddress.setUpdateTime(new Date());
        userAddress.setId(addressId);
        userAddress.setIsDefault(EnumInterface.Status.VALID.ordinal());
        updateOtherUnDefault(userAddress.getUserId(),EnumInterface.Status.INVALID.ordinal());
		userAddressMapper.updateByPrimaryKeySelective(userAddress);
	}

}
